package com.songyang.blog.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.songyang.blog.common.lang.Result;
import com.songyang.blog.entity.Post;
import com.songyang.blog.entity.User;
import com.songyang.blog.entity.UserMessage;
import com.songyang.blog.util.UploadUtil;
import com.songyang.blog.vo.UserMessageVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @GetMapping("/home")
    public String home() {
        User user = userService.getById(getProfileId());
        List<Post> postList = userService.getPosts(getProfileId());
        request.setAttribute("user", user);
        request.setAttribute("posts", postList);
        return "/user/home";
    }

    @GetMapping("/set")
    public String set() {
        User user = userService.getById(getProfileId());
        request.setAttribute("user", user);
        return "/user/set";
    }

    @ResponseBody
    @PostMapping("/set")
    public Result doSet(User user) {
        User temp = userService.getById(getProfileId());
        User profile = getProfile();
        if (StrUtil.isNotBlank(user.getAvatar())) {
            temp.setAvatar(user.getAvatar());
            userService.updateById(temp);
            profile.setAvatar(user.getAvatar());
            SecurityUtils.getSubject().getSession().setAttribute("profile", profile);
            return Result.success().action("/user/set#avatar");
        }
        if (StrUtil.isBlank(user.getUsername())) {
            return Result.fail("昵称不能为空!");
        }
        int count = userService.count(new QueryWrapper<User>()
                .eq("username", user.getUsername())
                .ne("id", getProfileId())
        );//检查这个昵称不包括自己有没有被使用
        if (count > 0) return Result.fail("该昵称已被占用");
        temp.setUsername(user.getUsername());
        temp.setGender(user.getGender());
        temp.setSign(user.getSign());
        userService.updateById(temp);
        profile.setUsername(temp.getUsername());
        profile.setSign(temp.getSign());//这里同步shiro的数据直接set就可以
        return Result.success().action("/user/set" + new Date());

    }

    @ResponseBody
    @PostMapping("/upload")
    public Result uploadAvatar(@RequestParam(value = "file") MultipartFile file) throws IOException {
        return uploadUtil.upload(UploadUtil.type_avatar, file);
    }

    @ResponseBody
    @PostMapping("/repass")
    public Result repass(String nowpass, String pass, String repass) {
        if (!pass.equals(repass)) {
            return Result.fail("两次密码不相同");
        }
        User user = userService.getById(getProfileId());
        String nowPassMd5 = SecureUtil.md5(nowpass);
        if (!nowPassMd5.equals(user.getPassword())) {
            return Result.fail("密码不正确");
        }
        user.setPassword(SecureUtil.md5(pass));
        userService.updateById(user);
        shiroUtils.logout();
        return Result.success("修改密码成功!请重新登录!").action("/");
    }

    @ResponseBody
    @GetMapping("/public")//发表的文章
    public Result userpublic() {
        IPage page = postService.page(getPage(), new QueryWrapper<Post>()
                .eq("user_id", getProfileId())
                .orderByDesc("created")
        );
        return Result.success(page);
    }

    @ResponseBody
    @GetMapping("/collection")//收藏的 文章
    public Result collection() {
        IPage page = postService.page(getPage(), new QueryWrapper<Post>()
                .inSql("id", "SELECT post_id FROM user_collection where user_id = " + getProfileId())
        );
        return Result.success(page);
    }

    @GetMapping("/mess")
    public String mess() {
        IPage<UserMessageVO> page = messageService.paging(getPage(), new QueryWrapper<UserMessage>()
                .eq("to_user_id", getProfileId())
                .orderByDesc("created")
        );
        // 把消息改成已读状态
        List<Long> ids = new ArrayList<>();
        for (UserMessageVO messageVo : page.getRecords()) {
            if (messageVo.getStatus() == 0) {
                ids.add(messageVo.getId());
            }
        }
        // 批量修改成已读
        messageService.updateToReaded(ids);
        request.setAttribute("pageData", page);
        return "/user/mess";
    }

    @GetMapping("/index")
    public String index() {
        return "/user/index";
    }

    @ResponseBody
    @PostMapping("/mess/remove")
    public Result messRemove(Long id, @RequestParam(defaultValue = "false") Boolean all) {
        boolean remove = messageService.remove(new QueryWrapper<UserMessage>()
                .eq("to_user_id", getProfileId())
                .eq(!all, "id", id));
        return remove ? Result.success().action("/user/mess") : Result.fail("删除失败!");
    }

    @ResponseBody
    @PostMapping("/mess/nums")
    public Map messNums() {
        int count = messageService.count(new QueryWrapper<UserMessage>()
                .eq("to_user_id", getProfileId())
                .eq("status", "0")
        );
        return MapUtil.builder("status", 0).put("count", count).build();
    }
}
